package com.shenghua.service.impl;

import com.alibaba.fastjson.JSON;
import com.shenghua.dao.mapper.RolesMapper;
import com.shenghua.dao.mapperX.RolesMapperX;
import com.shenghua.dao.model.Roles;
import com.shenghua.dao.model.RolesExample;
import com.shenghua.dao.model.User;
import com.shenghua.dao.page.Page;
import com.shenghua.service.RolesService;
import com.shenghua.utils.ListUtils;
import com.shenghua.utils.StringUtils;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/3/23.
 */
@Service
public class RolesServiceImpl implements RolesService {
    Logger logger = LoggerFactory.getLogger(RolesServiceImpl.class);
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private RolesMapperX rolesMapperX;

    @Override
    public Dto<Roles> addNewRoles(Roles roles) {
        Dto<Roles> dto = new Dto<>();
        if(null == roles){
            logger.debug("[RolesServiceImpl] addNewRoles 角色信息为空！");
            dto.ReturnFail(new Roles(), ErrorCode.PARAMETER_IS_NULL);
            return dto;
        }
        roles.setCreated(new Date());

        RolesExample rolesExample = new RolesExample();
        RolesExample.Criteria criteria = rolesExample.createCriteria();
        criteria.andRoleNameEqualTo(roles.getRoleName());
        List<Roles> rolesList = rolesMapper.selectByExample(rolesExample);
        if(ListUtils.isNotEmpty(rolesList)) {
            logger.error("[RolesServiceImpl] addNewRoles 角色已经存在！ roles={}", JSON.toJSONString(roles));
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_ADD_FAIL);
            return dto;
        }
        int result = rolesMapper.insert(roles);
        if(result<=0){
            logger.error("[RolesServiceImpl] addNewRoles 角色信息添加失败！");
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_ADD_FAIL);
            return dto;
        }
        dto.ReturnSuccess(roles,ErrorCode.ROLES_ADD_SUCCESS);
        logger.info("[RolesServiceImpl] addNewRoles 角色信息添加成功！");
        return dto;
    }

    @Override
    public Dto<Map<String, Object>> queryRolesByPage(Map<String, Object> params, Page page) {
        Dto<Map<String,Object>> dto = new Dto<>();
        if(null == params || params.size() == 0) {
            logger.debug("[RolesServiceImpl] queryRolesByPage 参数为空");
            dto.ReturnFail(null, ErrorCode.USER_QUERY_IS_NULL);
            return dto;
        }
        if(null == page){
            logger.debug("[RolesServiceImpl] queryRolesByPage 分页信息为空");
            dto.ReturnFail(null, ErrorCode.PAGE_IS_NULL);
            return dto;
        }
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 过滤查询条件
        Map<String,Object> map = new HashMap<>();
        if(null != params.get("roleName") && !"".equals(params.get("roleName"))){
            map.put("roleName",params.get("roleName"));
        }
        if(null != params.get("sign") && !"".equals(params.get("sign"))){
            map.put("sign",params.get("sign"));
        }
        if(null != params.get("status") && !"".equals(params.get("status"))){
            map.put("status",params.get("status"));
        }
        if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[RolesServiceImpl] queryRolesByPage 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        map.put("begin", page.getBegin());
        map.put("end", page.getLength());
        int total = 0;
        List<Roles> list = new ArrayList<>();
        list = rolesMapperX.selectRolesListByMap(map);
        total = rolesMapperX.countRolesByMap(map);
        logger.info("***********************");
        logger.info("[RolesServiceImpl] queryRolesByPage 查询到的记录总数："+String.valueOf(total));
        logger.info("[RolesServiceImpl] queryRolesByPage 查询到的记录信息："+ JSON.toJSONString(list));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("total",total);
        paramMap.put("rows", list);
        dto.ReturnSuccess(paramMap,ErrorCode.USER_Query_SUCCESS);
        return dto;
    }

    @Override
    public Dto<Roles> deleteRoles(Roles roles) {
        return null;
    }

    @Override
    public Roles selectRolesById(int id) {
        return null;
    }

    @Override
    public Dto<Map<String, Object>> countRoles(Map<String, Object> params) {
        return null;
    }

    @Override
    public Dto<Roles> editCurrentRoles(Roles roles) {
        Dto<Roles> dto = new Dto<>();
        if(null == roles){
            logger.debug("[RolesServiceImpl] editCurrentRoles 角色信息为空！");
            dto.ReturnFail(new Roles(), ErrorCode.PARAMETER_IS_NULL);
            return dto;
        }
        if(null == roles.getRoleName()){
            logger.debug("[RolesServiceImpl] editCurrentRoles 角色名称不能为空！");
            dto.ReturnFail(new Roles(), ErrorCode.PARAMETER_IS_NULL);
            return dto;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
        String updated = sdf.format(roles.getUpdated());
        try {
            roles.setUpdated(sdf.parse(updated));
        } catch (ParseException e) {
            e.printStackTrace();
            roles.setUpdated(new Date());
            logger.info("时间解析异常！");
        }
        int result = rolesMapper.updateByPrimaryKeySelective(roles);
        if(result<=0){
            logger.error("[RolesServiceImpl] editCurrentRoles 角色信息编辑失败！");
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_EDIT_FAIL);
            return dto;
        }
        dto.ReturnSuccess(roles,ErrorCode.ROLES_EDIT_SUCCESS);
        logger.info("[RolesServiceImpl] editCurrentRoles 角色信息编辑成功！");
        return dto;
    }

    /**
     * 下拉列表查询角色信息
     *
     * @return
     */
    @Override
    public String queryRolesForCombobox() {
        String result = "";
        List<Roles> rolesList = rolesMapperX.selectRolesListByMap(null);
        if(ListUtils.isNotEmpty(rolesList)) {
            result = JSON.toJSONString(rolesList);
        }

        return result;
    }
}
